using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Security.Cryptography;
using Managistics.Warehouse.Controllers.Interfaces;
using Managistics.Warehouse.Views.Interfaces;

namespace Managistics.Warehouse.Configuration
{
    public class LoadingScreen : ILoadingController
    {
        private Thread waiting;
        private string isThreadOf = string.Empty;

        public LoadingScreen()
        {
            this.isThreadOf = string.Empty;
        }

        public bool IsAlive
        {
            get
            {
                return waiting.IsAlive;
            }
            set { }
        }

        private void ShowWaiting()
        {
            ILoadingView loadingView = new LoadingForm();
            ((Form)loadingView).ShowDialog();
            while (true)
            {
                try
                {
                    ((Form)loadingView).Refresh();
                    Thread.Sleep(30);
                }
                catch (Exception)
                {
                    Thread.Sleep(30);
                }
            }
        }

        public void Run()
        {
            if (isThreadOf == string.Empty)
            {
                var bytes = new byte[16];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(bytes);
                }

                waiting = new Thread(new ThreadStart(ShowWaiting));
                waiting.Start();

                isThreadOf = GlobalApp.ThreadOfWaiting = BitConverter.ToString(bytes);
            }
        }

        public void Stop(string key)
        {
            if (waiting.IsAlive && isThreadOf == key)
            {
                waiting.Abort();
                isThreadOf = string.Empty;
            }
        }
    }
}
